using System;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using Microsoft.VisualStudio.Modeling;
using Microsoft.VisualStudio.Modeling.Design;

namespace DslCrossModelFramework.UI {
    public class ModelElementListTypeEditor : UITypeEditor {
        /// <summary>
        /// Overridden to specify that our editor is a modal form
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) {
            return UITypeEditorEditStyle.Modal;
        }


        /// <summary>
        /// Called by VS whenever the user clicks on the ellipsis in the 
        /// properties window for a property to which this editor is linked.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="provider"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override object EditValue(
            System.ComponentModel.ITypeDescriptorContext context,
            IServiceProvider provider,
            object value) {
            if (provider == null) {
                throw new ArgumentNullException("provider");
            }
            if (context == null) {
                throw new ArgumentNullException("context");
            }


            // Get a reference to the underlying property element
            ElementPropertyDescriptor descriptor = context.PropertyDescriptor as ElementPropertyDescriptor;
            ModelElement underlyingModelElement = descriptor.ModelElement;

            // context.Instance also returns a model element, but this will either
            // be the shape representing the underlying element (if you selected
            // the element via the design surface), or the underlying element 
            // itself (if you selected the element via the model explorer)
            //ModelElement element = context.Instance as ModelElement;

            // Create an instance of the windows forms editor
            IWindowsFormsEditorService service =
                (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));

            CrossModelManager manager = new CrossModelManager(underlyingModelElement.Store);
            ModelElementList dialog = new ModelElementList(manager);
            if (service.ShowDialog(dialog) == DialogResult.OK) {
                value = dialog.ModelElementReference;
                return value;
            }


            return value;
        }
    }
}